#include <QPixmap>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

#include "tileselectscene.h"

TileSelectScene::TileSelectScene()
{
    editing = false;
    selectedTile = QPoint(0,0);
}

void TileSelectScene::load(QString filename, qint32 tileW, qint32 tileH)
{
    pixmap = new QPixmap(filename);
    tileSizeX = tileW;
    tileSizeY = tileH;

    editing = true;
}

void TileSelectScene::drawForeground(QPainter *painter, const QRectF &)
{
    if (editing && pixmap != 0)
    {
        QPen blackPen = painter->pen();
        blackPen.setColor(QColor(0, 0, 0));
        painter->setPen(blackPen);

        for (qint32 i = 0; i <= pixmap->width() * tileSizeX; i+= tileSizeX)
        {
            QPointF start(i, 0);
            QPointF end(i, pixmap->height() * tileSizeY);

            painter->drawLine(start, end);
        }

        for (qint32 j = 0; j<= pixmap->height() * tileSizeY; j+= tileSizeY)
        {
            QPointF start(0, j);
            QPointF end(pixmap->width() * tileSizeX, j);

            painter->drawLine(start, end);
        }

        QRect selectedRect(selectedTile.x() * tileSizeX + 1, selectedTile.y() * tileSizeY + 1, tileSizeX - 2, tileSizeY - 2);

        QPen whitePen = painter->pen();
        whitePen.setColor(QColor(255, 255, 255));
        painter->setPen(whitePen);

        painter->drawRect(selectedRect);

    }
}

void TileSelectScene::drawBackground(QPainter *painter, const QRectF &)
{
    if (editing && pixmap != 0)
    {
        QRect rect(0, 0, pixmap->width(), pixmap->height());
        painter->drawPixmap(rect, *pixmap);
        setSceneRect(rect);
    }
}

void TileSelectScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if (editing)
    {
        if (mouseEvent->button() == Qt::LeftButton)
        {
            if (sceneRect().contains(mouseEvent->scenePos()))
            {
                QPoint tileInfo = getTileInfo(mouseEvent->scenePos());
                selectedTile = tileInfo;
                emit selectedTileChanged(getTileNum(tileInfo));
                invalidate(QRectF(), ForegroundLayer);
            }
        }
    }
}

 qint32 TileSelectScene::getTileNum(QPoint &tile) const
 {
     qint32 numHTiles = pixmap->width() / tileSizeX;
     return tile.y() * numHTiles + tile.x() % numHTiles;
 }

QPoint TileSelectScene::getTileInfo(QPointF position)
{
    return QPoint(position.x() / tileSizeX,
                    position.y() / tileSizeY);
}

TileSelectScene::~TileSelectScene()
{
    if (pixmap != 0)
    {
        delete pixmap;
    }
}
